import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/material.dart' show Icons;
import 'package:fnos_tv_desktop/application/configuration/configs.dart';
import 'package:fnos_tv_desktop/core/api/api.dart';
import 'package:provider/provider.dart';

import '../../core/model/user_info.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool obscureText = true;
  bool saveAccount = true;
  final host = TextEditingController();
  final username = TextEditingController();
  final password = TextEditingController();

  @override
  void initState() {
    host.text = Configs.app.savedHostUrl.value ?? '';
    username.text = Configs.app.savedUsername.value ?? '';
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _autoLogin();
    });
  }

  void _autoLogin() async {
    final host = Configs.app.savedHostUrl.value;
    final token = Configs.app.token.value;
    if (host?.isNotEmpty == true) {
      if (token != null) {
        Api(host).token = token;
        await _getUserInfo(context);
        if(mounted) {
          Navigator.of(context).pushNamed('/main');
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('images/bg_login.webp'),
          fit: BoxFit.cover,
        ),
      ),
      child: Center(
        child: Container(
          constraints: BoxConstraints(
            maxWidth: 448,
            maxHeight: 558,
            minWidth: 350,
            minHeight: 502,
          ),
          child: Card(
            padding: const EdgeInsets.symmetric(vertical: 60, horizontal: 50),
            borderRadius: BorderRadius.circular(24),
            borderColor: Colors.white.withAlpha(50),
            backgroundColor: Colors.black.withAlpha(200),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset('images/logo_h.png', width: 174, height: 50),
                const SizedBox(height: 24),

                // Text('飞牛影视', style: FluentTheme.of(context).typography.subtitle),
                // const SizedBox(height: 60),
                SizedBox(
                  height: 48,
                  child: TextBox(controller: host, placeholder: '服务器地址'),
                ),
                const SizedBox(height: 24),
                SizedBox(
                  height: 48,
                  child: TextBox(controller: username, placeholder: '用户名'),
                ),
                const SizedBox(height: 24),
                SizedBox(
                  height: 48,
                  child: TextBox(
                    controller: password,
                    placeholder: '密码',
                    obscureText: obscureText,
                    suffix: SizedBox(
                      width: 48,
                      height: 48,
                      child: IconButton(
                        icon: Icon(
                          obscureText ? Icons.visibility_off : Icons.visibility,
                          size: 16,
                        ),
                        onPressed: () {
                          setState(() {
                            obscureText = !obscureText;
                          });
                        },
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 24),
                Row(
                  children: [
                    Checkbox(
                      checked: saveAccount,
                      onChanged: (value) {
                        setState(() {
                          saveAccount = !saveAccount;
                        });
                      },
                      content: const Text('记住账号'),
                    ),
                    const Spacer(),
                    HyperlinkButton(
                      child: const Text('忘记密码?'),
                      onPressed: () {
                        displayInfoBar(
                          context,
                          builder: (context, close) {
                            return InfoBar(
                              severity: InfoBarSeverity.info,
                              title: const Text('啊哦 >_<'),
                              content: const Text('那可咋办呀……'),
                            );
                          },
                        );
                      },
                    ),
                  ],
                ),
                const SizedBox(height: 24),
                SizedBox(
                  height: 48,
                  child: FilledButton(
                    onPressed: () {
                      _doLogin(context);
                    },
                    child: Center(
                      child: Text(
                        '登录',
                        style: FluentTheme.of(context).typography.bodyLarge,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _doLogin(BuildContext context) async {
    final api = Api(host.text);
    final error = await api.loginWithPassword(username.text, password.text);
    if (error == null) {
      if (saveAccount) {
        Configs.app.savedHostUrl.value = host.text;
        Configs.app.savedUsername.value = username.text;
        Configs.app.token.value = api.token;
      }
      if (context.mounted) await _getUserInfo(context);
      if (context.mounted) Navigator.of(context).pushNamed('/main');
    } else {
      if (context.mounted) {
        displayInfoBar(
          context,
          builder: (context, close) {
            return InfoBar(
              severity: InfoBarSeverity.error,
              title: const Text('登录失败'),
              content: Text(error),
            );
          },
        );
      }
    }
  }

  Future<void> _getUserInfo(BuildContext context) async {
    final userInfo = await Api().getUserInfo();
    if (context.mounted) {
      context.read<UserInfo>().update(userInfo);
    }
  }
}
